<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-18 22:16:01
 * Desc:
 */

namespace app\base\model\user;

use think\Model;
use app\core\cache\{RedisCache, RedisKeys};

class UserWx extends Model
{
    protected $autoWriteTimestamp = false;
    protected $table = 'xy_user.xy_user_wx';

    const OFFICIAL_ACCOUNT_OPEN_ID_TYPE = 1;
    const MINI_PROGRAM_OPEN_ID_TYPE = 2;

    const SESSION_KEY_EXPR = 3 * 86400 - 60;//session_key有效期

    public function __construct($data = [])
    {
        parent::__construct($data);
        RedisCache::selectDB(config('redis_db_index.wx'));
    }

    public static function saveMiniProgramSessionKey($open_id, $session_key)
    {
        $key = RedisKeys::getMiniProgramSessionKey($open_id);
        return RedisCache::set($key, $session_key, self::SESSION_KEY_EXPR);
    }

    public static function getSessionKeyByOpenId($open_id)
    {
        $key = RedisKeys::getMiniProgramSessionKey($open_id);
        return RedisCache::get($key);
    }

    public static function insertWxInfo($data)
    {
        return self::create($data);
    }

    public static function updateWxInfo($where, $data)
    {
        return self::where($where)->update($data);
    }

    public static function getUserIdByUnionId($app_id, $union_id)
    {
        return self::where('union_id', $union_id)->where('app_id', $app_id)->find();
    }

    static public function getWxInfoByMiniProgramOpenId($app_id, $open_id)
    {
        return self::where('open_id', $open_id)->where('app_id', $app_id)->where('open_id_type',
            self::MINI_PROGRAM_OPEN_ID_TYPE)->find();
    }

    /**
     * 通过user_id获取信息
     * @param $user_id
     * @param $app_id
     * @param $open_id_type
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getByUserId($user_id, $app_id, $open_id_type)
    {
        return self::where('user_id', $user_id)->where('app_id', $app_id)->where('open_id_type', $open_id_type)->find();
    }

    public static function getOpenIdByUserId($user_id, $app_id, $open_id_type)
    {
        return self::where('user_id', $user_id)->where('app_id', $app_id)->where('open_id_type',
            $open_id_type)->value('open_id');
    }

    public static function saveMiniProgramDecryptedData($decrypted_data, $user_id = 0)
    {
        if (isset($decrypted_data['openId']) && isset($decrypted_data['watermark']['appid'])) {
            $app_id = $decrypted_data['watermark']['appid'];
            $open_id = $decrypted_data['openId'];

            $data = [
                'union_id' => $decrypted_data['unionId'] ?? '',
                'wx_nickname' => $decrypted_data['nickName'],
                'wx_gender' => $decrypted_data['gender'],
                'wx_avatar_url' => $decrypted_data['avatarUrl'],
                'wx_country' => $decrypted_data['country'],
                'wx_province' => $decrypted_data['province'],
                'wx_city' => $decrypted_data['city'],
                'is_follow' => 1,
                'first_bind_time' => date('Y-m-d H:i:s', $decrypted_data['watermark']['timestamp'])
            ];

            $where = [
                'open_id' => $open_id,
                'app_id' => $app_id,
                'open_id_type' => self::MINI_PROGRAM_OPEN_ID_TYPE
            ];

            if ($user_id) {
                $data['user_id'] = $user_id;
                //$where['user_id'] = $user_id;
            }


            $wx_log_id = self::where($where)->value('wx_id');
            if (empty($wx_log_id)) {
                $data = array_merge($where, $data);
                return self::create($data);
            } else {
                return self::where('wx_id', $wx_log_id)->update($data);
            }
        }

        return false;

    }

    public static function MiniProgramIsBind($user_id, $app_id = '')
    {
        if (empty($app_id)) {
            $default_info = config('weChatConfigList.default_mini_program');
            $app_id = $default_info['app_id'] ?? '';
        }

        if (empty($app_id)) {
            return false;
        }

        return self::field('open_id')->where('user_id', $user_id)->where('app_id', $app_id)->where('open_id_type',
            self::MINI_PROGRAM_OPEN_ID_TYPE)->where('is_follow', 1)->find();
    }
}